node {
    checkout scm

    def jenkins_buildnum = env.BUILD_NUMBER
    def docker_image
    def project_name_full = env.JOB_NAME
    def project_name_splitted = project_name_full.split("/")
    def project_name = project_name_splitted[0]
    def docker_registry
    def docker_registry_dev = 'https://registryw.blindage.org'
    def docker_registry_release = 'https://git.blindage.org'
    def docker_repository
    def docker_repository_dev = 'registryw.blindage.org/iam21h'
    def docker_repository_release = 'git.blindage.org/21h'
    def docker_auth
    def docker_auth_dev = 'registry'
    def docker_auth_release = 'gitea'
    def git_tag = env.TAG_NAME
    def git_branch = env.BRANCH_NAME
    def docker_image_tag = 'latest'

    if ( git_branch == "master" ) {
        docker_registry = "${docker_registry_dev}"
        docker_auth = "${docker_auth_dev}"
        docker_image_tag = "${git_branch}-${jenkins_buildnum}"
        docker_repository = "${docker_repository_dev}/${project_name}"
    }
    if ( git_tag != null ) {
        docker_registry = "${docker_registry_release}"
        docker_auth = "${docker_auth_release}"
        docker_image_tag = "${git_tag}"
        docker_repository = "${docker_repository_release}/${project_name}"
    }

    def docker_image_name = "${docker_repository}:${docker_image_tag}"

    echo "Building project ${project_name} (${docker_image_name})"

    stage('Build image') {
        try {
            writeFile file: "version/VERSION", text: "${docker_image_tag}"
            docker.build(docker_image_name)
            docker_image = docker.image(docker_image_name)
        } catch (Exception e) {
            error('Failed to build image', e.toString())
        }
    }

    stage('Push image') {
        try {
            docker.withRegistry("${docker_registry}", "${docker_auth}") {
                docker_image.push()
            }
        } catch (Exception e) {
            error('Failed to push image', e.toString())
        } finally {
            sh "docker rmi ${docker_image_name} || true"
        }
    }

    if ( git_tag != null ) {
        stage('Publish Helm chart') {
            sh "helm package helm_chart --app-version=${git_tag} --version=${git_tag} -d /var/artifacts/charts-repo"
            sh "helm repo update"
            sh "helm cm-push /var/artifacts/charts-repo/${project_name}-${git_tag}.tgz gitea"
            build(job: 'helm-charts-rebuild')
        }
        stage('Deploy') {
            sh "helm repo add 21h https://charts.blindage.org"
            sh "helm repo update"
            sh "helm upgrade ${project_name} --install -n operators --version ${git_tag} 21h/${project_name}"
        }
    }

}
